; (function (window) {
   var Stats = function() {
        var time = Date.now(),
        temp_time = time,
        diff_time = 0,

        min_num = 1 / 0,
        max_num = 0,
        s = 0,
        o = 1 / 0,
        a = 0,
        l = 0,

        new_time = 0;

        var domElement = document.createElement("div");
        domElement.id = "stats";
        domElement.style.cssText = "width:80px;opacity:0.9;cursor:pointer";

        var fps = document.createElement("div");
        fps.id = "fps";
        fps.style.cssText = "padding:0 0 3px 3px;text-align:left;background-color:#002", 
        domElement.appendChild(fps);

        var fpsText = document.createElement("div");
        fpsText.id = "fpsText", 
        fpsText.style.cssText = "color:#0ff;font-family:Helvetica,Arial,sans-serif;font-size:9px;font-weight:bold;line-height:15px", 
        fpsText.innerHTML = "FPS", 
        fps.appendChild(fpsText);

        var fpsGraph = document.createElement("div");
        for (fpsGraph.id = "fpsGraph", fpsGraph.style.cssText = "position:relative;width:74px;height:30px;background-color:#0ff", fps.appendChild(fpsGraph); 74 > fpsGraph.children.length;) {
            var span = document.createElement("span");
            span.style.cssText = "width:1px;height:30px;float:left;background-color:#113";
            fpsGraph.appendChild(span);
        }

        var ms = document.createElement("div");
        ms.id = "ms";
        ms.style.cssText = "padding:0 0 3px 3px;text-align:left;background-color:#020;display:none", 
        domElement.appendChild(ms);

        var msText = document.createElement("div");
        msText.id = "msText";
        msText.style.cssText = "color:#0f0;font-family:Helvetica,Arial,sans-serif;font-size:9px;font-weight:bold;line-height:15px", 
        msText.innerHTML = "MS", 
        ms.appendChild(msText);

        var msGraph = document.createElement("div");
        for (msGraph.id = "msGraph", msGraph.style.cssText = "position:relative;width:74px;height:30px;background-color:#0f0", ms.appendChild(msGraph); 74 > msGraph.children.length;) {
            var span = document.createElement("span");
            span.style.cssText = "width:1px;height:30px;float:left;background-color:#131";
            msGraph.appendChild(span)
        }

        var setMode = function(e) {
            switch (h = e) {
                case 0:
                    u.style.display = "block";
                    m.style.display = "none";
                    break;
                case 1:
                    u.style.display = "none";
                    m.style.display = "block";
            }
        };

        var changeHeight = function(e, t) {
            var i = e.appendChild(e.firstChild);
            i.style.height = t + "px"
        };

        return {
            REVISION: 11,
            domElement: domElement,
            setMode: setMode,
            begin: function() {
                time = Date.now()
            },
            end: function() {
                var new_time = Date.now();
                diff_time = new_time - time;
                min_num = Math.min(min_num, diff_time);
                max_num = Math.max(max_num, diff_time);
                msText.textContent = diff_time + " MS (" + min_num + "-" + max_num + ")";
                changeHeight(msGraph, Math.min(30, 30 - 30 * (diff_time / 200)));
                l++;

                if(new_time > temp_time + 1000){
                    s = Math.round(1000 * l / diff_time);
                    o = Math.min(o, s);
                    a = Math.max(a, s);
                    fpsText.textContent = s + " FPS (" + o + "-" + a + ")";
                    changeHeight(fpsGraph, Math.min(30, 30 - 30 * (s / 100)));
                    temp_time = new_time;
                    l = 0;
                }
                return new_time;
            },
            update: function() {
                time = this.end()
            }
        }
    };
  
    var ctx,
        hue,
        logo,
        form,
        buffer,
        target = {},
        tendrils = [],
        settings = {};

    settings.debug = false;
    settings.friction = 0.5;
    settings.trails = 50;
    settings.size = 50;
    settings.dampening = 0.25;
    settings.tension = 0.98;

    Math.TWO_PI = Math.PI * 2;

    function Oscillator(options) {
        this.init(options || {});
    }

    Oscillator.prototype = (function () {

        var value = 0;

        return {

            init: function (options) {
                this.phase = options.phase || 0;
                this.offset = options.offset || 0;
                this.frequency = options.frequency || 0.001;
                this.amplitude = options.amplitude || 1;
            },

            update: function () {
                this.phase += this.frequency;
                value = this.offset + Math.sin(this.phase) * this.amplitude;
                return value;
            },

            value: function () {
                return value;
            }
        };

    })();

    function Tendril(options) {
        this.init(options || {});
    }

    Tendril.prototype = (function () {

        function Node() {
            this.x = 0;
            this.y = 0;
            this.vy = 0;
            this.vx = 0;
        }

        return {

            init: function (options) {

                this.spring = options.spring + (Math.random() * 0.1) - 0.05;
                this.friction = settings.friction + (Math.random() * 0.01) - 0.005;
                this.nodes = [];

                for (var i = 0, node; i < settings.size; i++) {

                    node = new Node();
                    node.x = target.x;
                    node.y = target.y;

                    this.nodes.push(node);

                }
            },

            update: function () {

                var spring = this.spring,
                    node = this.nodes[0];

                node.vx += (target.x - node.x) * spring;
                node.vy += (target.y - node.y) * spring;

                for (var prev, i = 0, n = this.nodes.length; i < n; i++) {

                    node = this.nodes[i];

                    if (i > 0) {

                        prev = this.nodes[i - 1];

                        node.vx += (prev.x - node.x) * spring;
                        node.vy += (prev.y - node.y) * spring;
                        node.vx += prev.vx * settings.dampening;
                        node.vy += prev.vy * settings.dampening;
                    }

                    node.vx *= this.friction;
                    node.vy *= this.friction;
                    node.x += node.vx;
                    node.y += node.vy;

                    spring *= settings.tension;
                }

            },

            draw: function () {

                var x = this.nodes[0].x,
                    y = this.nodes[0].y,
                    a, b;

                ctx.beginPath();
                ctx.moveTo(x, y);

                for (var i = 1, n = this.nodes.length - 2; i < n; i++) {

                    a = this.nodes[i];
                    b = this.nodes[i + 1];
                    x = (a.x + b.x) * 0.5;
                    y = (a.y + b.y) * 0.5;

                    ctx.quadraticCurveTo(a.x, a.y, x, y);
                }

                a = this.nodes[i];
                b = this.nodes[i + 1];

                ctx.quadraticCurveTo(a.x, a.y, b.x, b.y);
                ctx.stroke();
                ctx.closePath();

            }
        };

    })();

    function init(event) {

        document.removeEventListener('mousemove', init);
        document.removeEventListener('touchstart', init);

        document.addEventListener('mousemove', mousemove);
        document.addEventListener('touchmove', mousemove);
        document.addEventListener('touchstart', touchstart);

        mousemove(event);
        reset();
        loop();
    }

    function reset() {
        tendrils = [];
        for (var i = 0; i < settings.trails; i++) {
            tendrils.push(new Tendril({
                spring: 0.45 + 0.025 * (i / settings.trails)
            }));
        }
    }

    function loop() {

        if (!ctx.running) return;

        ctx.globalCompositeOperation = 'source-over';
        ctx.fillStyle = 'rgba(8,5,16,0.4)';
        ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        ctx.globalCompositeOperation = 'lighter';
        
        ctx.lineWidth = 1;
        ctx.strokeStyle = 'hsla(' + Math.round(hue.update()) + ',90%,50%,0.25)';

        for (var i = 0, tendril; i < settings.trails; i++) {
            tendril = tendrils[i];
            tendril.update();
            tendril.draw();
        }

        ctx.frame++;
        ctx.stats.update();
        requestAnimFrame(loop);
    }

    function resize() {
        ctx.canvas.width = window.innerWidth;
        ctx.canvas.height = window.innerHeight;
    }

    function start() {
        if (!ctx.running) {
            ctx.running = true;
            loop();
        }
    }

    function stop() {
        ctx.running = false;
    }

    function mousemove(event) {
        if (event.touches) {
            target.x = event.touches[0].pageX;
            target.y = event.touches[0].pageY;
        } else {
            target.x = event.clientX
            target.y = event.clientY;
        }
        event.preventDefault();
    }

    function touchstart(event) {
        if (event.touches.length == 1) {
            target.x = event.touches[0].pageX;
            target.y = event.touches[0].pageY;
        }
    }

    window.requestAnimFrame = (function () {
        return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (fn) { window.setTimeout(fn, 1000 / 60) };
    })();

    window.onload = function () {
        ctx = document.getElementById('canvas').getContext('2d');
        ctx.stats = new Stats();
        ctx.running = true;
        ctx.frame = 1;

        hue = new Oscillator({
            phase: Math.random() * Math.TWO_PI,
            amplitude: 200,
            frequency: 0.0015,
            offset: 285
        });

        document.addEventListener('mousemove', init);
        document.addEventListener('touchstart', init);
        document.body.addEventListener('orientationchange', resize);
        window.addEventListener('resize', resize);
        window.addEventListener('focus', start);
        window.addEventListener('blur', stop);
        resize();
    };

})(window);